package media

import (
	"errors"
	"server/common"

	"github.com/mitchellh/mapstructure"
)

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) checkProduceReqData(data common.CreateProducerReqData) error {
	// Check if transport ID is provided
	if data.TransportId == "" {
		return errors.New("transport ID is required in produce request")
	}

	// Check if router ID is provided
	if data.RouterId == "" {
		return errors.New("router ID is required in produce request")
	}

	// Check if RTP parameters are provided
	if data.RtpParameters == nil {
		return errors.New("RTP parameters are required in produce request")
	}

	// Check if router exists
	if !s.RouterExists(data.RouterId) {
		return errors.New("router does not exist")
	}

	// Check if transport exists
	if !s.TransportExists(data.RouterId, data.TransportId) {
		return errors.New("transport does not exist in the router")
	}

	return nil
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) handleCreateProducerReq(msg common.Message) {
	LOG(msg.Rid).WithField("msg", common.ToJson(msg)).Info("handling create produce request")

	var reqData common.CreateProducerReqData
	if err := mapstructure.Decode(msg.Data, &reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to decode produce request data")
		return
	}

	if err := s.checkProduceReqData(reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("produce request data validation failed")
		return
	}

	producer, err := s.CreateProducer(msg.Rid, reqData)
	if err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to create producer")
		return
	}

	resMsg := common.Message{
		Rid: msg.Rid,
		Cmd: common.CREATE_PRODUCER_RES,
		Data: common.ResMsgData{
			Code: 0,
			Msg:  "Produce request handled successfully",
			Data: common.CreateProducerResData{
				RouterId:   reqData.RouterId,
				ProducerId: producer.Id(),
			},
		},
	}
	if err := s.wsClient.Send(resMsg); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to send produce response")
	}
}
